#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>

#include "configure.h"
#include "function.h"

Configure *Configure::instance_ = NULL;

Configure::Configure() {}

Configure::~Configure() {
	std::vector<LPConfItem>::iterator it;
	for(it = configure_item_list_.begin(); it != configure_item_list_.end(); ++it) {
		delete (*it);
	}
	configure_item_list_.clear();
	return;
}

//装载配置文件
bool Configure::Load(const char *configure_name) {
	FILE *fp;
	fp = fopen(configure_name, "r");
	if(fp == NULL) {
		return false;
	}
	char line_buf[501];

	//读取数据
	while(!feof(fp)) {
		//逐行读取，每行不超过500个字符
		if(fgets(line_buf, 500, fp) == NULL)
			continue;
		//跳过空行
		if(line_buf[0] == 0)
			continue;
		//跳过注释行
		if(*line_buf == ';' || *line_buf == ' ' || *line_buf == '#' || *line_buf == '\t' || *line_buf == '\n')
			continue;
//循环处理读取字符串后的换行符、回车、空格
lplprocstring:
		if(strlen(line_buf) > 0) {
			if(line_buf[strlen(line_buf)-1] == 10 || line_buf[strlen(line_buf)-1] == 13 || line_buf[strlen(line_buf)-1] == 32) {
				line_buf[strlen(line_buf)-1] = 0;
				goto lplprocstring;
			}
		}

		if(line_buf[0] == 0)
			continue;
		if(*line_buf == '[')
			continue;

		//开始处理得到的字符串
		char *tmp = strchr(line_buf, '=');
		if(tmp != NULL) {
			LPConfItem configure_item = new ConfItem;
			memset(configure_item, 0, sizeof(ConfItem));
			strncpy(configure_item->item_name, line_buf, (int)(tmp - line_buf));
			strcpy(configure_item->item_content, tmp+1);

			Rtrim(configure_item->item_name);
			Ltrim(configure_item->item_name);
			Rtrim(configure_item->item_content);
			Ltrim(configure_item->item_content);

			configure_item_list_.push_back(configure_item);
		}
	}
	fclose(fp);
	return true;
}

const char *Configure::GetString(const char *item_name) {
	std::vector<LPConfItem>::iterator it;
	for(it = configure_item_list_.begin(); it != configure_item_list_.end(); ++it) {
		if(strcasecmp((*it)->item_name,item_name) == 0) {
			return (*it)->item_content;
		}
	}
	return NULL;
}


int Configure::GetIntDefault(const char *item_name, int def) {
	std::vector<LPConfItem>::iterator it;
	for(it = configure_item_list_.begin(); it != configure_item_list_.end(); ++it) {
		if(strcasecmp((*it)->item_name, item_name) == 0) {
			return atoi((*it)->item_content);
		}
	}
	return def;
}
